package blue.global.encrypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import blue.global.util.NumberUtil;

/**
 * 消息摘要算法，封装了MD5和SHA-1两种算法
 * 
 * @author zhengj
 * @since 1.0
 * @date 2008-12-22
 */
public class MessageDigestUtil
{
	private static MessageDigest md5;
	private static MessageDigest sha1;

	static
	{
		try
		{
			md5 = MessageDigest.getInstance("md5");
			sha1 = MessageDigest.getInstance("sha1");
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}

	/**
	 * 用MD5算法加密
	 * 
	 * @param src 密码原文
	 * @return MD5信息摘要
	 */
	public static String getMD5(String src)
	{
		String msg = null;
		try
		{
			byte[] dest = src.getBytes("utf-8");
			msg =  NumberUtil.toHexString(md5.digest(dest));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 用SHA-1算法加密
	 * 
	 * @param src 密码原文
	 * @return SHA-1信息摘要
	 */
	public static String getSHA1(String src)
	{
		String msg = null;
		try
		{
			byte[] dest = src.getBytes("utf-8");
			msg =  NumberUtil.toHexString(sha1.digest(dest));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 用MD5算法比较密码原文与密文是否相等
	 * 
	 * @param src 密码原文
	 * @param md MD5信息摘要
	 * @return 相等返回true，否则返回false
	 */
	public static boolean equalMD5(String src, String md)
	{
		if (src == null || md == null)
			return false;
		return md.equals(getMD5(src));
	}

	/**
	 * 用SHA-1算法比较密码原文与密文是否相等
	 * 
	 * @param src 密码原文
	 * @param md SHA-1信息摘要
	 * @return 相等返回true，否则返回false
	 */
	public static boolean equalSHA1(String src, String md)
	{
		if (src == null || md == null)
			return false;
		return md.equals(getSHA1(src));
	}
}
